<!DOCTYPE html>
<html>
<head>
    <script>
    
        var inspectItem = null;
        var tabsWithGL = [];
        
        // Pull out toolbar items
        var toolbarItems = safari.extension.toolbarItems;
        for (var n = 0; n < toolbarItems.length; n++) {
            var item = toolbarItems[n];
            if (item.command == "inspectToggle") {
                inspectItem = item;
            }
        }

        safari.application.addEventListener("validate", function (event) {
            var tab = event.target.browserWindow.activeTab;
            switch (event.command) {
                case "inspectToggle":
                    event.target.disabled = (tabsWithGL.indexOf(tab) == -1);
                    break;
            }
        }, false);        
        
        safari.application.addEventListener("command", function (event) {
            var tab = event.currentTarget.activeBrowserWindow.activeTab;
            switch (event.command) {
                case "inspectToggle":
                    tab.page.dispatchMessage("message", {});
                    break;
            }
        }, false);
        
        safari.application.addEventListener("message", function (event) {
            var message = event.message;
            var tab = event.target.browserWindow.activeTab;
            
            if (message.present) {
                tabsWithGL.push(tab);
            } else {
                for (var n = 0; n < tabsWithGL.length; n++) {
                    if (tabsWithGL[n] === tab) {
                        tabsWithGL.splice(n, 1);
                        break;
                    }
                }
            }
            
            // Revalidate toolbar item
            inspectItem.validate();
        }, false);
        
    </script>
</head>
</html>
